<template>
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="计划名称">
          <el-input v-model="searchParam.name" placeholder="请输入计划名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-tree-select v-model="searchParam.organizationId" :data="workRoomList" check-strictly
                          :props="{ children: 'sonList', label: 'orgName', value: 'id' }" style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
          <el-button icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          列表信息
          <el-icon>
            <house-icon/>
          </el-icon>
        </div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 350px)" :loading="isLoading">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            {{ (paginationParams.current - 1) * paginationParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="计划名称" align="center"/>
        <el-table-column prop="equipmentInspectionType" label="计划类型" align="center">
          <template #default="scope">
            {{ InspectionType?.find(i => i.value === scope.row.equipmentInspectionType)?.label }}
          </template>
        </el-table-column>
        <el-table-column prop="teamLeaderName" label="执行人" align="center"/>
        <el-table-column prop="cycleSettingId" label="周期" align="center">
          <template #default="scope">
            {{ cycleSetData?.find(i => i.id === scope.row.cycleSettingId)?.name }}
          </template>
        </el-table-column>
        <el-table-column prop="duration"  label="预计耗时（min）" align="center"/>
        <el-table-column prop="organizationName" label="所属部门" align="center"/>
        <el-table-column v-for="col in columns" :key="col.tableKey" :prop="col.tableKey" :label="col.tableChineseKey"
                         align="center"/>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" size="small" plain text :icon="Edit">编辑</el-button>
            <el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="paginationParams.current"
                       v-model:page-size="paginationParams.pageSize" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>

    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="1100" top="3vh">
      <el-form :model="formData" label-width="150" ref="ruleFormRef" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划名称" required prop="name">
              <el-input v-model="formData.name" placeholder="请输入计划名称" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划类型" prop="equipmentInspectionType">
              <el-select v-model="formData.equipmentInspectionType" placeholder="请选择计划类型" style="width: 300px">
                <el-option v-for="item in InspectionType" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行人" prop="teamLeaderId">
              <el-select v-model="formData.teamLeaderId" placeholder="请选择执行人" filterable style="width: 300px">
                <el-option v-for="item in userPersonData" :key="item.id" :label="item.nickname" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周期" prop="cycleSettingId">
              <el-select v-model="formData.cycleSettingId" placeholder="请选择周期" style="width: 300px">
                <el-option v-for="item in cycleSetData" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" required prop="organizationId">
              <el-tree-select v-model="formData.organizationId" :data="workRoomList" check-strictly
                              :props="{ children: 'sonList', label: 'orgName', value: 'id' }" @change="handleOrganizationChange" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备" prop="equipmentList">
              <el-select v-model="formData.equipmentList" placeholder="请选择设备" filterable style="width: 835px"   clearable multiple>
                <el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentCode"
                           :value="item.id">
                  <span style="float: left">{{ item.equipmentCode }}</span>
                  <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                    {{ item.equipmentName }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计耗时（min）" prop="duration">
              <el-input-number v-model="formData.duration" :min="0" style="width:300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="activate">
              <el-switch v-model="formData.activate"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" required prop="description">
              <el-input type="textarea" v-model="formData.description" placeholder="请输入描述" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="点巡检内容">
            </el-form-item>
          </el-col>
          <el-col :span="12" v-for="(input, index) in formData.inspectionItemJson" :key="index">
            <el-form-item>
              <el-row style="display: flex">
                <div style="display: flex;width: 100%;align-items: flex-end;margin: 0 20px 10px 0">
                  <el-input type="textarea" v-model="input.content" placeholder="请输入点巡检内容" style="width: 300px"/>
                  <el-button type="text" @click="addInput" style="margin-left: 10px"
                             :icon="Plus" v-if="index === 0">新建
                  </el-button>
                  <el-button type="text" @click="removeInput(index)" style="margin-left: 10px; color: red; "
                             :icon="Delete" v-if="index !== 0">删除
                  </el-button>
                </div>
              </el-row>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-for="col in columns" :key="col.tableKey">
            <el-form-item :label="col.tableChineseKey" :prop="col.tableKey">
              <el-input v-model="formData[col.tableKey]" :placeholder="`请输入${col.tableChineseKey}`"
                        style="width: 300px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog" title="管理列信息">
      <el-button :icon="Plus" @click="showAddColumnDialog2 = true; columnDialogTitle = '新建'" type="primary"
                 style="margin-bottom: 20px;">新建列
      </el-button>
      <el-table :data="columns">
        <el-table-column prop="tableChineseKey" label="列名称" align="center"/>
        <el-table-column prop="tableKey" label="列编码" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button @click="editColumn(scope.row, scope.$index)" size="small" icon="Edit">编辑</el-button>
            <el-button @click="deleteColumn(scope.row, scope.$index)" size="small" type="danger"
                       icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="showAddColumnDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog2" :title="columnDialogTitle">
      <el-form>
        <el-form-item label="列名称">
          <el-input v-model="newColumn.tableChineseKey" placeholder="请输入列名称"/>
        </el-form-item>
        <el-form-item label="列Key">
          <el-input v-model="newColumn.tableKey" placeholder="请输入列Key"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddColumnDialog2 = false">取消</el-button>
        <el-button type="primary" @click="addColumn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import SearchForm from '@/components/SearchForm.vue';
import {useToolData} from '@/hooks/device/creatPlan';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {computed, onMounted, ref, watch} from 'vue';
import {
  cycleSettingAll
} from '@/api/device/creatPlan';

const {
  searchParam,
  paginationParams,
  pageTotal,
  paginatedData,
  searchFields,
  handleSearch,
  handleSizeChange,
  handleCurrentChange,
  addTool,
  deleteTool,
  fetchPageData,
  isLoading,
  ruleFormRef,
  rules,
  formData,
  types,
  InspectionType,
  equipmentData,
  restForem,
  userPersonData,
  toolRegisterData,
  moldType
} = useToolData();

// 缓存key
const CACHE_KEY = 'device_plan_search_params';

onMounted(() => {
  // 尝试从缓存中读取搜索参数
  const cachedParams = localStorage.getItem(CACHE_KEY);
  if (cachedParams) {
    try {
      searchParam.value = JSON.parse(cachedParams);
    } catch (e) {
      console.error('解析缓存的搜索参数失败', e);
    }
  }

  fetchPageData({...searchParam.value, type: 1});
  moldType.value = 1;
  getColumnsList();
  getOptions();
});

// 监听搜索参数变化，缓存到localStorage
watch(searchParam, (newVal) => {
  localStorage.setItem(CACHE_KEY, JSON.stringify(newVal));
}, { deep: true });

const resetSearch = () => {
  searchParam.value = {};
  // 清除缓存
  localStorage.removeItem(CACHE_KEY);
  handleSearch();
};

const cycleSetData = ref([]);
const getOptions = () => {
  cycleSettingAll({type: 1}).then(res => {
    cycleSetData.value = res.data;
  });

  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
};

// 动态列和新列的数据
const columns = ref([
  {tableChineseKey: '自定义列1', tableKey: 'tableKey', visible: true},
  {tableChineseKey: '自定义列2', tableKey: 'tableKey', visible: true}
]);


const handleOrganizationChange = (value) => {
  axiosInstance.post('/api/basedataEquipment/getAll', {organizationId: value}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    // equipmentData.value = res.data;
    formData.value.equipmentList = res.data.map(item => item.id);
  });
};

const showAddColumnDialog = ref(false);
const showAddColumnDialog2 = ref(false);
const columnDialogTitle = ref('');
const columnIndexNumber = ref(0);
const workRoomList = ref([]);//车间
const newColumn = ref({
  tableChineseKey: '',
  tableKey: '',
  visible: true,
  id: ''
});

const addInput = () => {
  formData.value.inspectionItemJson.push({content: ''});
};
const cleanEquipment = () => {
  formData.value.equipmentList = undefined;
};
const removeInput = (index) => {
  formData.value.inspectionItemJson.splice(index, 1);
};

// 查询列
const getColumnsList = () => {
  axiosInstance.post('/api/dynamicTableExtension/getPage',
      {page: 1, pageSize: 999, tableName: 'tooling'}
  ).then(res => {
    const {data, code, message} = res;
    if (code === 200) {
      columns.value = data.records;
    }
  });
};

// 新建列
const addColumn = () => {
  if (newColumn.value.tableKey && newColumn.value.tableChineseKey) {
    if (columnDialogTitle.value === '新建') {
      axiosInstance.post('/api/dynamicTableExtension/save', {
        'frontendType': 'INPUT',
        'tableName': 'tooling',
        'tableKey': newColumn.value.tableKey,
        'tableChineseKey': newColumn.value.tableChineseKey
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('新建列成功');
          getColumnsList();
          newColumn.value = {tableKey: '', tableChineseKey: '', visible: true};
          showAddColumnDialog2.value = false;
        }
      });
    } else {
      axiosInstance.put('/api/dynamicTableExtension/update', {
        'frontendType': 'INPUT',
        'tableName': 'tooling',
        'tableKey': newColumn.value.tableKey,
        'tableChineseKey': newColumn.value.tableChineseKey,
        'id': newColumn.value.id
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('修改成功');
          getColumnsList();
          showAddColumnDialog2.value = false;
        }
      });
    }
  }
};

// 编辑列
const editColumn = (row, index) => {
  columnIndexNumber.value = index;
  columnDialogTitle.value = '编辑';
  showAddColumnDialog2.value = true;
  newColumn.value.tableChineseKey = row.tableChineseKey;
  newColumn.value.tableKey = row.tableKey;
  newColumn.value.id = row.id;
};

// 删除列
const deleteColumn = (row, index) => {
  axiosInstance.delete('/api/dynamicTableExtension/delete', {
    data: {
      ids: [row.id]
    }
  }).then(res => {
    if (res.code === 200) {
      getColumnsList();
      ElMessage.success('修改成功');
    }
  });
};

const toolList = ref([]);
const isEdit = ref(false);
const showCrud = ref(false);
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});

// 新建记录
const handleAdd = () => {
  isEdit.value = false;
  formData.value = {
    ...restForem.value,
    type: 1
  };
  showCrud.value = true;
};

// 编辑记录
const handleEdit = (row) => {
  isEdit.value = true;
  formData.value = {
    ...row,
    inspectionItemJson: JSON.parse(row.inspectionItemJson),
    equipmentList: row.equipmentList.split(','),
    type: 1
  };
  showCrud.value = true;
};

// 删除记录
const handleDel = (row) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteTool(row.id);
  }).catch(() => {
  });
};

// 保存记录
const handleSave = async () => {
  const formDataObject = columns.value.reduce((acc, col) => {
    acc[col.tableKey] = formData.value[col.tableKey];
    return acc;
  }, {});
  formData.value.extension = formDataObject;
  await addTool(formData.value, (() => {
    showCrud.value = false;
  }));
};
</script>

<style scoped>
</style>